<?php

class RwtGerminasiModel{
	private $db;
	private $subbagian;
	
	private $validColumn;

	private $data;
	
	private $sort_by;
	private $sort_order;

	private $search_keyword;
	private $search_field;

	private $limit;
	
	function RwtGerminasiModel($dbObject){
		$this->subbagian 	= 'rwt_germinasi';		
		$this->db 			= $dbObject;

		$this->validColumn  = array(
			'tgl_perawatan', 
			'label_tandan', 
			'penanggung_jawab', 
			'jml_pekerja', 
			'biaya_pekerja', 
			'biaya_material', 
			'jenis_perawatan', 
			'kondisi_awal', 
			'kondisi_akhir', 
			'catatan',
			'subbagian',
			
			'nama_peralatan',
			'jml_peralatan',
			'nama_material',
			'jml_material',
			'satuan_material',
			'harga_material'
			);
		
		// settting up configuration
		if(($this->start=$this->getGET('start')) == NULL)
			$this->start = 0;

		$this->sort_by 			= $this->getGET('sort_by');
		$this->sort_order 		= $this->getGET('sort_order');
		$this->search_keyword	= $this->getGET('search_keyword');
		$this->search_field		= $this->getGET('search_field');

		if(($this->limit=$this->getGET('limit')) == NULL)
			$this->limit = 50;				
	}
	
	private function getGET($param){
		if( isset( $_GET[$param] ) && $_GET[$param] != '' )
			return $_GET[$param];
		else
			return NULL;
	}
	
	public function countAll(){
		$where = $this->prepareWhereClause();	
		$q = "SELECT COUNT(*) FROM `caramel_operational`.`produksi_perawatan` $where";
		
		$this->total_record = $this->db->get_var($q);
		
		return $this->total_record;
	}	
	
	private function prepareWhereClause(){
		$where = '';
		if( $this->search_keyword && $this->search_field ){
			switch($this->search_field){
					case 'jenis_perawatan':
						$where = "WHERE `subbagian`='rwt_germinasi' AND `id` IN (SELECT `perawatan_id` FROM `caramel_operational`.`produksi_perawatan_jenis` WHERE `jenis` LIKE '".$this->search_keyword."')";
						break;
					case 'material':
						$where = "WHERE `subbagian`='rwt_germinasi' AND `id` IN (SELECT `perawatan_id` FROM `caramel_operational`.`produksi_perawatan_material` WHERE `nama` LIKE '".$this->search_keyword."')";
						break;
					case 'peralatan':
						$where = "WHERE `subbagian`='rwt_germinasi' AND `id` IN (SELECT `perawatan_id` FROM `caramel_operational`.`produksi_perawatan_peralatan` WHERE `nama` LIKE '".$this->search_keyword."')";
						break;
					default:
						$where = "WHERE `subbagian`='rwt_germinasi' AND ".$this->search_field."='".$this->search_keyword."'";
			}
		}
		else{
			$where = $where = "WHERE `subbagian`='rwt_germinasi' ";
		}
		
		return $where;
	}
	
	private function getDetailPerawatan($id, $detail){
		$q = '';
		switch($detail){
			case 'material':
				$q = "SELECT `nama`, `jumlah`, `satuan` FROM `caramel_operational`.`produksi_perawatan_material` WHERE `perawatan_id`='".$id."'";
				break;
			case 'jenis_perawatan':
				$q = "SELECT `jenis` as `jenis_perawatan` FROM `caramel_operational`.`produksi_perawatan_jenis` WHERE `perawatan_id`='".$id."'";
				break;
			case 'peralatan':
				$q = "SELECT `nama`, `jumlah` FROM `caramel_operational`.`produksi_perawatan_peralatan` WHERE `perawatan_id`='".$id."'";
				break;				
		}
		$result = array();
		$r = $this->db->get_results($q, ARRAY_A);
		if( $r )	
			foreach($r as $j) $result[] = $j;
		
		return $result;
	}
	
	public function search(){			
		$where = $this->prepareWhereClause();
		
		// get data
		if( $this->sort_by )
			$q = "
			SELECT 
				`id`, `tgl_perawatan`, `label_tandan`, `penanggung_jawab`, `jml_pekerja`, `biaya_pekerja`, `biaya_material`, `kondisi_awal`, `catatan`, `kondisi_akhir`
			FROM  `caramel_operational`.`produksi_perawatan` $where
			ORDER BY ".$this->sort_by." ".$this->sort_order." LIMIT ".$this->start.",".$this->limit."";
		else
			$q = "
			SELECT 
				`id`, `tgl_perawatan`, `label_tandan`, `penanggung_jawab`, `jml_pekerja`, `biaya_pekerja`, `biaya_material`, `kondisi_awal`, `catatan`, `kondisi_akhir`
			FROM  `caramel_operational`.`produksi_perawatan` $where ORDER BY `tgl_perawatan` DESC
			LIMIT ".$this->start.",".$this->limit."";
		
		$this->result = $this->db->get_results($q, ARRAY_A);
		// detail
		if( count($this->result) > 0 ){
			foreach($this->result as &$r){
				$r['jenis_perawatan'] = $this->getDetailPerawatan($r['id'], 'jenis_perawatan');
				$r['material'] 		  = $this->getDetailPerawatan($r['id'], 'material');
				$r['peralatan'] 	  = $this->getDetailPerawatan($r['id'], 'peralatan');
			}
		}
		
		return $this->result;
	}

	public function getResult(){
		return $this->result;
	}
		
	function format($data){
		$result = array();
		foreach($this->validColumn as $v){
			if( isset($data[$v]) )
				$result[$v] = $data[$v];
			else
				$result[$v] = NULL;
		}
		
		return $result;
	}
	
	private function insertRwtGerminasi(){
		$dataRwtGerminasi = array();
		$perawatanColumn = array(
			'tgl_perawatan', 
			'label_tandan', 
			'penanggung_jawab', 
			'jml_pekerja', 
			'biaya_pekerja', 
			'biaya_material',  
			'kondisi_awal', 
			'kondisi_akhir', 
			'catatan',
			'subbagian'
		);
		
		// copy dari $data ke $dataRwtGerminasi
		foreach($perawatanColumn as $c){
			$dataRwtGerminasi[$c] = $this->data[$c];
		}
		
		$qHeader = "(`".implode($perawatanColumn, "`, `")."`)";
		$qBody   = "('".implode($dataRwtGerminasi, "', '")."')";
		
		$query = "INSERT INTO `caramel_operational`.`produksi_perawatan` ".$qHeader." VALUES ".$qBody;
		$this->db->query($query);
		
		$id = $this->db->get_var("SELECT MAX(`Id`) FROM `caramel_operational`.`produksi_perawatan`");
		
		return $id;
	}
	
	private function insertJenisPerawatan($id){
		$dataJenisPerawatan = array();
		$jenisPerawatanColumn = array(
			'jenis_perawatan'
		);
		
		// copy dari $data ke $dataJenisPerawatan
		foreach($jenisPerawatanColumn as $c){
			$dataJenisPerawatan[$c] = $this->data[$c];
		}
		
		if( count($dataJenisPerawatan['jenis_perawatan']) > 0 ){
		
			$qHeader = "(`perawatan_id`, `jenis`)";			
			$query   = "INSERT INTO `caramel_operational`.`produksi_perawatan_jenis` ".$qHeader." VALUES ";
			$temp    = '';
			// looping through all material
			for($i=0; $i<count($dataJenisPerawatan['jenis_perawatan']); $i++){			
				$qBody   = "('".$id."', '".$dataJenisPerawatan['jenis_perawatan'][$i]."')";
				$temp[]  = $qBody;
			}
			
			$query .= implode($temp, ",").';';
			
			$this->db->query($query);
		}
	}
	
	private function insertPeralatan($id){
		$dataPeralatan = array();
		$peralatanColumn = array(
			'nama_peralatan', 
			'jml_peralatan'
		);
		
		// copy dari $data ke $dataPeralatan
		foreach($peralatanColumn as $c){
			$dataPeralatan[$c] = $this->data[$c];
		}
		
		if( count($dataPeralatan['nama_peralatan']) > 0 ){
		
			$qHeader = "(`perawatan_id`, `nama`, `jumlah`)";			
			$query   = "INSERT INTO `caramel_operational`.`produksi_perawatan_peralatan` ".$qHeader." VALUES ";
			$temp    = '';
			// looping through all material
			for($i=0; $i<count($dataPeralatan['nama_peralatan']); $i++){			
				$qBody   = "('".$id."', '".$dataPeralatan['nama_peralatan'][$i]."', '".$dataPeralatan['jml_peralatan'][$i]."')";
				$temp[]  = $qBody;
			}
			
			$query .= implode($temp, ",").';';
			
			$this->db->query($query);
		}
	}
	
	private function insertMaterial($id){
		$dataMaterial = array();
		$materialColumn = array(
			'nama_material', 
			'jml_material', 
			'satuan_material',
			'harga_material',
		);
		
		// copy dari $data ke $dataMaterial
		foreach($materialColumn as $c){
			$dataMaterial[$c] = $this->data[$c];
		}
		
		if( count($dataMaterial['nama_material']) > 0 ){
		
			$qHeader = "(`perawatan_id`, `nama`, `jumlah`, `satuan`, `harga`)";			
			$query   = "INSERT INTO `caramel_operational`.`produksi_perawatan_material` ".$qHeader." VALUES ";
			$temp    = '';
			// looping through all material
			for($i=0; $i<count($dataMaterial['nama_material']); $i++){			
				$qBody   = "('".$id."', '".$dataMaterial['nama_material'][$i]."', '".$dataMaterial['jml_material'][$i]."', '".$dataMaterial['satuan_material'][$i]."', '".$dataMaterial['harga_material'][$i]."')";
				$temp[]  = $qBody;
			}
			
			$query .= implode($temp, ",").';';
			
			$this->db->query($query);
		}
	}	
	
	
	function put($data){		
		$this->data	= $this->format($data);// buang field2 yang tidak dibutuhkan

		if( $this->isExist() == FALSE ){
			// perawatan
			$id = $this->insertRwtGerminasi();
			// jenis perawatan
			$this->insertJenisPerawatan($id);	
			// material
			$this->insertMaterial($id);		
			// peralatan
			$this->insertPeralatan($id);
		}
		else{
			return INSERT_FAIL_DUPLICATE;
		}	
	}	
	
	function isExist(){
		// single query
		// melihat duplikasi dari field yang unique dari table ybs
		// cek primary key
		$whereClause = "`tgl_perawatan`='".$this->data['tgl_perawatan']."' AND `label_tandan`='".$this->data['label_tandan']."' AND `subbagian`='".$this->subbagian."'";
		$query 		 = "SELECT COUNT(*) FROM `caramel_operational`.`produksi_perawatan` WHERE ".$whereClause;
		$count = $this->db->get_var($query);
		
		if( $count > 0 )
			return TRUE;
			
		return FALSE; // tidak ada data yang dicari... no duplicate		
	}
    
    public function delete($id){
        $q[] = "
        DELETE FROM `caramel_operational`.`produksi_perawatan` 
        WHERE `id`='$id'";
        
        // jenis
        $q[] = "
        DELETE FROM `caramel_operational`.`produksi_perawatan_jenis` 
        WHERE `perawatan_id`='$id'";
        
        // material
        $q[] = "
        DELETE FROM `caramel_operational`.`produksi_perawatan_material` 
        WHERE `perawatan_id`='$id'";
        
        // peralatan
        $q[] = "
        DELETE FROM `caramel_operational`.`produksi_perawatan_peralatan` 
        WHERE `perawatan_id`='$id'";
        
        
        foreach($q as $query){
            $this->db->query($query);
        }
    }
}
?>